package com.broada.apm.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.broada.apm.dao.UserDao;
import com.broada.apm.model.PagingList;
import com.broada.apm.model.User;
import com.broada.apm.model.UserToken;

public class MysqlUserDao extends MysqlAbstractDao implements UserDao {
	
	public static final String USER_NAMESPACE = "com.broada.apm.dao.UserDao.";

	@Override
	public void addUser(User user) {
		getSqlSession().insert(USER_NAMESPACE + "addUser", user);
	}

	@Override
	public void updateUserPassword(String id, String password) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("id", id);
		paramMap.put("password", password);
		getSqlSession().update(USER_NAMESPACE + "updateUserPassword", paramMap);
	}

	@Override
	public void updateUserNameAndRole(String id, String name, int role) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("name", name);
		paramMap.put("role", role);
		getSqlSession().update(USER_NAMESPACE + "updateUserNameAndRole", paramMap);
	}

	@Override
	public void updateUserStatus(String id, int status) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("status", status);
		getSqlSession().update(USER_NAMESPACE + "updateUserStatus", paramMap);
	}

	@Override
	public void deleteUser(User user) {
		getSqlSession().delete(USER_NAMESPACE + "deleteUser", user);
	}

	@Override
	public User getUserById(String userId) {
		return getSqlSession().selectOne(USER_NAMESPACE + "getUserById", userId);
	}

	@Override
	public PagingList<User> getPagingUser(int pageIndex, int pageSize) {
		PagingList<User> page = new PagingList<User>();
		page.setStartPage(pageIndex);
		page.setPageSize(pageSize);
		List<User> users = getSqlSession().selectList(USER_NAMESPACE + "getPagingUser", page);
		page.setData(users);
		PagingList.pagingHandler(pageIndex, pageSize, (int)page.getTotalRecords(), page);
		return page;
	}

	@Override
	public User getUserByAccount(String account) {
		return getSqlSession().selectOne(USER_NAMESPACE + "getUserByAccount", account);
	}

	@Override
	public void deleteUserToken(String key) {
		getSqlSession().delete(USER_NAMESPACE + "deleteUserToken", key);
	}

	@Override
	public UserToken getUserToken(String key) {
		return getSqlSession().selectOne(USER_NAMESPACE + "getUserToken", key);
	}

	@Override
	public List<UserToken> getAllUserTokens() {
		return getSqlSession().selectList(USER_NAMESPACE + "getAllUserTokens");
	}

	@Override
	public void addUserToken(UserToken userToken) {
		getSqlSession().insert(USER_NAMESPACE + "addUserToken", userToken);
	}

}
